package com.iuv.shortpromotion.task;

import com.iuv.shortpromotion.domain.DemoSmsPromotionTbl;
import com.iuv.shortpromotion.service.DemoSmsPromotionService;
import com.iuv.shortpromotion.util.ShortPromotionUtil;
import com.iuv.shortpromotion.vo.QuerySmsTemplateResponse;

import java.util.Timer;
import java.util.TimerTask;

/**
 * 定时任务，查询模板的申请状态
 * @author mic
 * @date 2020-11-12
 */
public class SendBatchSmsTask extends TimerTask {
    private Timer timer;
    private int count;
    private String templateCode;
    private DemoSmsPromotionTbl demoSmsPromotionTbl;
    private DemoSmsPromotionService demoSmsPromotionService;

    public SendBatchSmsTask(String templateCode, DemoSmsPromotionTbl demoSmsPromotionTbl, DemoSmsPromotionService demoSmsPromotionService) {
        this.templateCode = templateCode;
        this.demoSmsPromotionTbl = demoSmsPromotionTbl;
        this.demoSmsPromotionService = demoSmsPromotionService;
        count = 0;
        this.timer = new Timer();
        //两个小时查询一次

        timer.schedule(this, 2 * 60 * 60 * 1000, 2 * 60 * 60 * 1000);

    }

    @Override
    public void run() {
        count++;
        QuerySmsTemplateResponse querySmsTemplateResponse = ShortPromotionUtil.querySmsTemplate(templateCode);
        //查询成功
        if (querySmsTemplateResponse != null || "OK".equalsIgnoreCase(querySmsTemplateResponse.getCode())) {
            if (querySmsTemplateResponse.getTemplateStatus().equals(0)) {
                /**
                 * 模板审核中
                 */
                demoSmsPromotionTbl.setPushStatus(0);
                demoSmsPromotionTbl.setErrorMessage("模板审核中");
                demoSmsPromotionService.update(demoSmsPromotionTbl);
            } else if (querySmsTemplateResponse.getTemplateStatus().equals(1)) {
                /**
                 * 模板审核通过
                 * 群发短信
                 */
                demoSmsPromotionTbl.setTemplateCode(querySmsTemplateResponse.getTemplateCode());
                demoSmsPromotionService.sendBatchSms(demoSmsPromotionTbl);
                this.cancel();
           } else if (querySmsTemplateResponse.getTemplateStatus().equals(2)) {
                /**
                 * 模板审核失败，请在返回参数Reason中查看审核失败原因
                 */
                demoSmsPromotionTbl.setPushStatus(0);
                demoSmsPromotionTbl.setErrorMessage("模板审核失败，失败原因:" + querySmsTemplateResponse.getReason());
                demoSmsPromotionService.update(demoSmsPromotionTbl);
                this.cancel();
            }
        }
        //最多查询试两次
        if (count >= 2) {
            this.cancel();
        }
    }

    @Override
    public boolean cancel() {
        timer.cancel();
        return super.cancel();
    }
}
